<template>
	<view class="begin-action-container">
		<!-- 顶部时间和完成按钮 -->
		<view class="header" v-if="!allTrainingCompleted">
			<view class="timer">{{ formattedTime }}</view>
			<view class="complete-btn" @click="completeWorkout">完成</view>
		</view>

		<!-- 今日训练已完成提示 -->
		<view class="training-completed" v-if="allTrainingCompleted">
			<view class="completed-icon">✓</view>
			<view class="completed-text">今日训练已完成，请明日再来</view>
		</view>

		<!-- 训练动作列表 -->
		<view class="exercise-list" v-else>
			<view class="exercise-card" v-for="(exercise, exerciseIndex) in exercises" :key="exerciseIndex">
				<!-- 训练部位和名称 -->
				<view class="part-tag">{{ exercise.part }}训练</view>
				<view class="exercise-header">
					<view class="exercise-name">{{ exercise.name }}</view>
					<view class="vbt-tag" v-if="exercise.vbt" @click="goVBT(exercise)">VBT <text class="arrow">»</text>
					</view>
					<!-- 添加删除动作按钮 -->
					<view class="delete-exercise-btn" @click="deleteExercise(exerciseIndex)">
						<view class="tn-icon-close"></view>
					</view>
				</view>

				<!-- 组数列表 -->
				<view class="sets-container">
					<!-- 组数行 -->
					<view class="set-row" v-for="(set, setIndex) in exercise.sets" :key="setIndex">
						<view class="set-label"
							:class="{ 'warm-up': set.isWarmUp, 'active': set.completed || set.timerActive }"
							@click="toggleSetActive(exercise, setIndex)">
							{{ set.isWarmUp ? '热' : set.index }}
							<image class="corner-icon"
								:src="set.isActive ? '/pagesTool/static/active_icon.png' : '/pagesTool/static/icon.png'">
							</image>
						</view>
						<view class="weight-input" :class="{ 'active': set.completed || set.timerActive }">
							<input type="number" v-model="set.weight"
								:disabled="set.completed || hasActiveSet(exercise) && !set.timerActive"
								@focus="checkCanEdit(exercise, set)" @blur="validateInput(set, 'weight')" />
							<text class="unit">kg</text>
						</view>
						<view class="reps-input" :class="{ 'active': set.completed || set.timerActive }">
							<input type="number" v-model="set.reps"
								:disabled="set.completed || hasActiveSet(exercise) && !set.timerActive"
								@focus="checkCanEdit(exercise, set)" @blur="validateInput(set, 'reps')" />
							<text class="unit">次</text>
						</view>
						<view class="timer-display" v-if="set.timerActive">{{ set.remainingTime }}s</view>
						<view class="timer-display" v-else></view>
						<view class="action-buttons">
							<view class="check-btn" @click="completeSet(exercise, set)"
								:class="{ 'active': set.completed || set.timerActive }">
								<view class="check-icon" :class="{ 'completed': set.completed }">
									<view class="tn-icon-success"></view>
								</view>
							</view>
							<view class="copy-btn" @click="copySet(exercise, setIndex)" v-if="set.isActive">
								<view class="copy-icon">
									<view class="tn-icon-copy"></view>
								</view>
							</view>
							<view class="delete-btn" @click="deleteSet(exercise, setIndex)" v-if="set.isActive">
								<view class="delete-icon">
									<view class="tn-icon-close-square"></view>
								</view>
							</view>
						</view>
					</view>

					<!-- 添加组按钮 -->
					<view class="add-set-row" @click="addSet(exercise)" v-if="exercise.sets.length < 10">
						<view class="add-set-btn">
							<text class="add-icon">+</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部添加动作按钮 -->
		<view class="add-action-btn" @click="goaction" v-if="!allTrainingCompleted">
			<text>添加动作</text>
		</view>
	</view>
</template>

<script>
	import VueEvent from "../../VueEvent.js";
	import {
		getTrainNum,
		saveTodayPlan
	} from "../../apis/schedule.js";
	export default {
		data() {
			return {
				// 训练开始时间
				startTime: new Date(),
				// 当前时间
				currentTime: new Date(),
				// 定时器
				timer: null,
				// 训练动作列表
				exercises: [],
				// 倒计时定时器
				countdownTimers: {},
				// 是否所有训练都已完成
				allTrainingCompleted: false,
				// 默认动作映射表
				defaultExercises: {
					0: {
						part: '胸部',
						name: '卧推',
						vbt: true
					},
					1: {
						part: '背部',
						name: '俯身划船',
						vbt: false
					},
					2: {
						part: '肩部',
						name: '站姿推肩',
						vbt: false
					},
					3: {
						part: '臀部',
						name: '罗马尼亚硬拉',
						vbt: true
					},
					4: {
						part: '腿部',
						name: '深蹲',
						vbt: true
					},
					5: {
						part: '手臂',
						name: '哑铃弯举',
						vbt: false
					}
				},
				action_map:[1,3,5,8,0,1000],
			};
		},
		computed: {
			// 格式化显示时间
			formattedTime() {
				const diff = Math.floor((this.currentTime - this.startTime) / 1000);
				const minutes = Math.floor(diff / 60);
				const seconds = diff % 60;
				return `${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
			}
		},
		created() {
			// 获取训练数据
			this.fetchTrainingData();
		},
		mounted() {
			// 启动计时器
			this.timer = setInterval(() => {
				this.currentTime = new Date();
			}, 1000);
		},
		methods: {
			goVBT(e) {
				let actionVbtMap = {
					'深蹲': 0,
					'卧推': 1,
					'硬拉': 2,
					'俯身划船': 3,
					'高翻': 4,
					'站姿推肩': 5,
					'高位下拉': 6,
					'坐姿推肩': 7,
					'罗马尼亚硬拉': 8,
					'直腿硬拉': 9,
				}
				console.log("actionVBTmap",actionVbtMap[e.name]);
				VueEvent.add_action(actionVbtMap[e.name])
				
				let obj = {
					'id': '',
					data: []
				}
				VueEvent.sharedData.train_record.push(obj)
				uni.navigateTo({
					url: '/pagesExtra/login/login'

				})
			},
			// 获取训练数据
			fetchTrainingData() {
				getTrainNum().then(res => {
					console.log("result!！！", res)
					if (res.status == 200 && res.data && res.data.length > 0) {
						VueEvent.sharedData.train_record = res.data
						VueEvent.sharedData.train_id = res.data[0].id
						
						for (let i = 0; i < res.data.length; i++) {
							let num = res.data[i].trainNum;
							let trainData = []
							for (let j = 0; j < num; j++) {
								let obj = {
									'id': j,
									'lrm': 0,
									'num': 0
								}
								trainData.push(obj)
							}
							VueEvent.sharedData.train_record[i].trainData = trainData
						}
						console.log("本地缓存展示", VueEvent.sharedData.train_record)
						// 保存id，用于后续保存操作
						if (res.data[0] && res.data[0].id) {
							this._trainDataId = res.data[0].id;
						}

						// 清空现有训练列表
						this.exercises = [];

						// 过滤掉trainNum为0的动作
						const validTrainings = res.data.filter(item => item.trainNum > 0);

						// 检查是否所有训练都已完成
						if (validTrainings.length === 0) {
							this.allTrainingCompleted = true;
							return;
						}

						// 根据接口返回数据生成训练动作列表
						validTrainings.forEach(item => {
							const trainBody = item.trainBody;
							const trainNum = item.trainNum || 3; // 默认3组

							// 获取对应部位的默认动作
							const defaultExercise = this.defaultExercises[trainBody] || {
								part: '未知部位',
								name: '未知动作',
								vbt: false
							};

							// 创建训练动作
							const exercise = {
								part: defaultExercise.part,
								name: defaultExercise.name,
								vbt: defaultExercise.vbt,
								restTime: 60,
								sets: []
							};

							// 添加热身组
							exercise.sets.push({
								index: '热',
								isWarmUp: true,
								weight: 0,
								reps: 0,
								completed: false,
								timerActive: false,
								remainingTime: 60,
								isActive: false
							});

							// 根据trainNum添加训练组
							for (let i = 1; i <= trainNum; i++) {
								exercise.sets.push({
									index: i,
									isWarmUp: false,
									weight: 0,
									reps: 0,
									completed: false,
									timerActive: false,
									remainingTime: 60,
									isActive: false
								});
							}

							// 添加到训练列表
							this.exercises.push(exercise);
						});
					} else {
						// 接口请求失败或数据为空，显示提示
						uni.showToast({
							title: '请先去日程页制定训练计划',
							icon: 'none'
						});
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/schedule/schedule'
							})
						}, 1500)
					}
				}).catch(err => {
					console.error('获取训练数据出错:', err);
					uni.showToast({
						title: '获取训练数据出错',
						icon: 'none'
					});
				});
			},
			// 切换组的激活状态
			toggleSetActive(exercise, setIndex) {
				// 直接切换当前组的激活状态，不影响其他组
				exercise.sets[setIndex].isActive = !exercise.sets[setIndex].isActive;
			},
			goaction() {
				uni.navigateTo({
					url: '/pagesExtra/action/action'
				})
			},
			// 复制一组训练
			copySet(exercise, setIndex) {
				if (exercise.sets.length >= 10) {
					uni.showToast({
						title: '最多只能添加10组',
						icon: 'none'
					});
					return;
				}

				const currentSet = exercise.sets[setIndex];
				const newSet = {
					index: currentSet.isWarmUp ? 1 : currentSet.index + 1,
					isWarmUp: false,
					weight: currentSet.weight,
					reps: currentSet.reps,
					completed: false,
					timerActive: false,
					remainingTime: exercise.restTime,
					isActive: false
				};

				// 在当前组后插入新组
				exercise.sets.splice(setIndex + 1, 0, newSet);

				// 更新后续组的索引
				for (let i = setIndex + 2; i < exercise.sets.length; i++) {
					if (!exercise.sets[i].isWarmUp) {
						exercise.sets[i].index = newSet.index + (i - (setIndex + 1));
					}
				}
			},
			// 删除一组训练
			deleteSet(exercise, setIndex) {
				// 不允许删除热身组
				if (exercise.sets[setIndex].isWarmUp) {
					uni.showToast({
						title: '热身组不能删除',
						icon: 'none'
					});
					return;
				}

				// 不允许删除正在进行的组
				if (exercise.sets[setIndex].timerActive) {
					uni.showToast({
						title: '正在进行的组不能删除',
						icon: 'none'
					});
					return;
				}

				// 确认删除
				uni.showModal({
					title: '删除确认',
					content: '确定要删除这组训练吗？',
					success: (res) => {
						if (res.confirm) {
							// 删除组
							exercise.sets.splice(setIndex, 1);

							// 更新后续组的索引
							for (let i = setIndex; i < exercise.sets.length; i++) {
								if (!exercise.sets[i].isWarmUp) {
									exercise.sets[i].index = i;
								}
							}
						}
					}
				});
			},
			// 完成训练
			completeWorkout() {
				uni.showModal({
					title: '完成训练',
					content: '确定要结束本次训练吗？',
					success: (res) => {
						if (res.confirm) {
							// 构建保存训练记录的参数
							const saveData = this.exercises.map(exercise => {
								// 获取训练部位索引
								let trainBodyIndex = 0;
								for (const key in this.defaultExercises) {
									if (this.defaultExercises[key].part === exercise.part) {
										trainBodyIndex = parseInt(key);
										break;
									}
								}

								// 计算非热身组的数量
								const trainZuShu = exercise.sets.filter(set => !set.isWarmUp).length;

								// 构建每组训练的详细信息
								const todayTrainOtherInfo = exercise.sets.map(set => ({
									trainWeight: set.weight.toString(),
									trainCiShu: set.reps.toString()
								}));

								return {
									id: this._trainDataId || "", // 使用从getTrainNum接口获取的id
									trainBody: trainBodyIndex.toString(),
									trainZuShu: trainZuShu.toString(),
									trainAction: exercise.name,
									todayTrainOtherInfo
								};
							});
							console.log('保存参数', saveData);

							// 调用保存接口
							saveTodayPlan(saveData).then(res => {
								if (res.status == 200) {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									});
									// 返回上一页
									uni.navigateBack();
								} else {
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									});
								}
							}).catch(err => {
								console.error('保存训练数据出错:', err);
								uni.showToast({
									title: '保存训练数据出错',
									icon: 'none'
								});
							});
						}
					}
				});
			},

			// 验证输入
			validateInput(set, type) {
				if (set[type] === '' || isNaN(set[type])) {
					set[type] = 0;
				} else {
					set[type] = parseInt(set[type]);
				}
			},

			// 检查是否有正在进行的组
			hasActiveSet(exercise) {
				return exercise.sets.some(s => s.timerActive);
			},

			// 检查是否可以编辑当前组
			checkCanEdit(exercise, set) {
				// 如果已完成，不允许编辑
				if (set.completed) return false;

				// 如果有正在进行的组且不是当前组，不允许编辑
				if (this.hasActiveSet(exercise) && !set.timerActive) {
					uni.showToast({
						title: '当前已有正在进行的组，请完成后再试',
						icon: 'none'
					});
					return false;
				}

				// 检查前面的组是否都已完成
				const setIndex = exercise.sets.findIndex(s => s === set);
				for (let i = 0; i < setIndex; i++) {
					if (!exercise.sets[i].completed) {
						uni.showToast({
							title: '请先完成前面的组',
							icon: 'none'
						});
						return false;
					}
				}

				return true;
			},

			// 完成一组训练
			completeSet(exercise, set) {
				// 如果已完成，询问是否重新开始
				if (set.completed) {
					uni.showModal({
						title: '提示',
						content: '是否要重新开始这组训练？',
						success: (res) => {
							if (res.confirm) {
								// 重置该组状态
								set.completed = false;
								set.timerActive = false;
								set.remainingTime = exercise.restTime;
							}
						}
					});
					return;
				}

				// 如果有正在进行的组且不是当前组，不允许操作
				if (this.hasActiveSet(exercise) && !set.timerActive) {
					uni.showToast({
						title: '当前已有正在进行的组，请完成后再试',
						icon: 'none'
					});
					return;
				}

				// 检查前面的组是否都已完成
				const setIndex = exercise.sets.findIndex(s => s === set);
				for (let i = 0; i < setIndex; i++) {
					if (!exercise.sets[i].completed) {
						uni.showToast({
							title: '请先完成前面的组',
							icon: 'none'
						});
						return;
					}
				}

				// 检查重量和次数是否已输入且大于0
				if (set.weight <= 0 || set.reps <= 0) {
					uni.showToast({
						title: '请先输入有效的重量和次数',
						icon: 'none'
					});
					return;
				}

				// 如果正在倒计时，标记为已完成
				if (set.timerActive) {
					set.timerActive = false;
					set.completed = true;

					// 清除倒计时
					const timerId = `${exercise.name}_${set.index}_${Date.now()}`;
					if (this.countdownTimers[timerId]) {
						clearInterval(this.countdownTimers[timerId]);
						delete this.countdownTimers[timerId];
					}
					return;
				}

				// 启动倒计时
				set.timerActive = true;
				set.remainingTime = exercise.restTime;

				// 生成唯一ID用于管理定时器
				const timerId = `${exercise.name}_${set.index}_${Date.now()}`;

				// 创建倒计时定时器
				this.countdownTimers[timerId] = setInterval(() => {
					if (set.remainingTime > 0) {
						set.remainingTime--;
					} else {
						// 倒计时结束
						set.timerActive = false;
						set.completed = true;
						clearInterval(this.countdownTimers[timerId]);
						delete this.countdownTimers[timerId];

						// 可以添加提示音或震动
						uni.vibrateShort();
					}
				}, 1000);
			},

			// 添加新的一组
			addSet(exercise) {
				if (exercise.sets.length >= 10) return;

				const newIndex = exercise.sets.length;
				exercise.sets.push({
					index: newIndex,
					isWarmUp: false,
					weight: 0,
					reps: 0,
					completed: false,
					timerActive: false,
					remainingTime: exercise.restTime,
					isActive: false
				});
			},

			// 删除训练动作
			deleteExercise(exerciseIndex) {
				// 检查是否有正在进行的组
				if (this.exercises[exerciseIndex].sets.some(set => set.timerActive)) {
					uni.showToast({
						title: '有正在进行的组，不能删除',
						icon: 'none'
					});
					return;
				}

				// 确认删除
				uni.showModal({
					title: '删除确认',
					content: '确定要删除这个训练动作吗？',
					success: (res) => {
						if (res.confirm) {
							// 删除动作
							this.exercises.splice(exerciseIndex, 1);

							// 如果删除后没有动作了，可以提示用户
							if (this.exercises.length === 0) {
								uni.showToast({
									title: '请添加训练动作',
									icon: 'none'
								});
							}
						}
					}
				});
			},
		}
	};
</script>

<style lang="less" scoped>
	.begin-action-container {
		padding: 30rpx;
		min-height: 100vh;
		background-color: #f9f9f9;
		position: relative;
		padding-bottom: 120rpx;

		// 顶部区域
		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 40rpx;

			.timer {
				font-size: 60rpx;
				font-weight: bold;
			}

			.complete-btn {
				background-color: #6e58aa;
				color: white;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				font-size: 28rpx;
			}
		}

		// 训练动作列表
		.exercise-list {
			.exercise-card {
				background-color: white;
				border-radius: 20rpx;
				padding: 30rpx;
				margin-bottom: 30rpx;
				position: relative;

				.part-tag {
					width: fit-content;
					font-size: 24rpx;
					color: #6e58aa;
					background-color: rgba(110, 88, 170, 0.1);
					padding: 6rpx 18rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
				}

				.exercise-header {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;


					.exercise-name {
						font-size: 32rpx;
						font-weight: bold;
						flex: 1;
					}

					.vbt-tag {
						font-size: 24rpx;
						color: #6e58aa;
						border: 1px solid #6e58aa;
						padding: 4rpx 12rpx;
						border-radius: 8rpx;
						margin-right: 40rpx; // 为删除按钮留出空间

						.arrow {
							font-weight: bold;
						}
					}

					// 删除动作按钮样式
					.delete-exercise-btn {
						width: 40rpx;
						height: 40rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						position: absolute;
						right: 10px;
						top: 10px;

						.tn-icon-close-square {
							color: #adadad;
							font-size: 36rpx;
						}

						&:active {
							opacity: 0.7;
						}
					}
				}

				.sets-container {
					.set-row {
						display: flex;
						align-items: center;
						height: 80rpx;
						margin-bottom: 10rpx;

						&.header-row {
							height: 60rpx;
							color: #999;
							font-size: 24rpx;
						}

						.set-label {
							width: 50rpx;
							height: 60rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 28rpx;
							font-weight: bold;
							border-radius: 10rpx;
							background-color: #f0f0f0;
							margin-right: 10rpx;
							position: relative; // 添加相对定位，用于放置角标

							.corner-icon {
								position: absolute;
								right: 0;
								bottom: 0;
								width: 16rpx;
								height: 16rpx;
							}

							&.warm-up {
								background-color: #6e58aa;
								color: white;
							}

							&.active {
								background-color: #6e58aa;
								color: white;
							}
						}

						.weight-input,
						.reps-input {
							width: 120rpx;
							height: 70rpx;
							background-color: #f0f0f0;
							border-radius: 10rpx;
							margin: 0 20rpx;
							position: relative;

							input {
								width: 100%;
								height: 100%;
								text-align: center;
								font-size: 28rpx;
								font-weight: bold;
								background-color: transparent;
							}

							.unit {
								position: absolute;
								right: 10rpx;
								bottom: 10%;
								font-size: 20rpx;
								font-weight: normal;
								color: #999;
							}

							&.active {
								background-color: #6e58aa;

								input {
									color: white;
								}

								.unit {
									color: white;
								}
							}
						}

						.timer-display {
							flex: 1;
							text-align: center;
							font-size: 28rpx;
							color: #6e58aa;
							font-weight: bold;
						}

						.action-buttons {
							display: flex;
							align-items: center;
							gap: 10rpx;

							.check-btn {
								width: 70rpx;
								height: 70rpx;
								display: flex;
								align-items: center;
								justify-content: center;

								&.active {
									.check-icon {
										background-color: #6e58aa;

										.check-mark {
											color: white;
										}
									}
								}

								.check-icon {
									width: 70rpx;
									height: 70rpx;
									border-radius: 8rpx;
									background-color: #f0f0f0;
									display: flex;
									align-items: center;
									justify-content: center;

									.check-mark {
										color: #666;
										font-size: 36rpx;
									}

									&.completed {
										background-color: #6e58aa;

										.check-mark {
											color: white;
										}
									}
								}
							}

							.copy-btn {
								width: 70rpx;
								height: 70rpx;
								display: flex;
								align-items: center;
								justify-content: center;

								.copy-icon {
									width: 70rpx;
									height: 70rpx;
									border-radius: 8rpx;
									background-color: #f0f0f0;
									display: flex;
									align-items: center;
									justify-content: center;

									.tn-icon-copy {
										// color: white;
										font-size: 36rpx;
									}
								}
							}

							.delete-btn {
								width: 70rpx;
								height: 70rpx;
								display: flex;
								align-items: center;
								justify-content: center;

								.delete-icon {
									width: 70rpx;
									height: 70rpx;
									border-radius: 8rpx;
									background-color: #f0f0f0;
									display: flex;
									align-items: center;
									justify-content: center;

									.tn-icon-close-square {
										// color: white;
										font-size: 36rpx;
									}
								}
							}
						}
					}

					.add-set-row {
						display: flex;
						justify-content: flex-end;
						margin-top: 20rpx;

						.add-set-btn {
							width: 60rpx;
							height: 60rpx;
							background-color: rgba(110, 88, 170, 0.7);
							border-radius: 8rpx;
							display: flex;
							align-items: center;
							justify-content: center;

							.add-icon {
								color: white;
								font-size: 40rpx;
								font-weight: bold;
							}
						}
					}
				}
			}
		}

		// 底部添加动作按钮
		.add-action-btn {
			position: fixed;
			bottom: 30rpx;
			left: 50%;
			transform: translateX(-50%);
			width: 300rpx;
			height: 80rpx;
			background-color: #fff;
			border-radius: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			font-size: 28rpx;
			color: #6e58aa;
			border: 1px solid rgba(110, 88, 170, 0.3);
		}
	}
</style>
<style lang="less" scoped>
	page {
		margin: 0;
		padding: 0;
		height: 100%;
		width: 100%;
		/* background-color: #f2f2f3; */
	}

	// 去掉页面滚动条
	::-webkit-scrollbar {
		display: none !important;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}

	/* 训练完成提示样式 */
	.training-completed {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 80vh;
		text-align: center;
	}

	.completed-icon {
		font-size: 80rpx;
		color: #4cd964;
		background-color: rgba(76, 217, 100, 0.1);
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
	}

	.completed-text {
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
	}
</style>